/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bookshop.dao;

import com.bookshop.entity.Customer;
import com.bookshop.exception.EBookshopException;
import java.util.List;
import javax.ejb.Singleton;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Thibault
 */
@Singleton(mappedName = "com.bookshop.dao.customer")
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class DaoCustomerImpl implements IDaoCustomerLocal, IDaoCustomerRemote {
    
    @PersistenceContext
    private EntityManager em;

    @Override
    public Customer findCustomerById(int id) {
        try {
            return (Customer) em.createNamedQuery("Customer.findById").setParameter("id", id).getSingleResult();
        } catch (Throwable th) {
            throw new EBookshopException(th.getMessage(), th);
        }
    }
    
    @Override
    public Customer findCustomerByLoginAndPassword(String login, String password) {
        try {
            
            List<Customer> query = em.createQuery("SELECT c FROM Customer c WHERE c.login = :login and c.password = :password")
                    .setParameter("login", login)
                    .setParameter("password", password).getResultList();
            if (query.size()>0){
                return query.get(0);
            } else {
                return null;
            }
//            return (Customer) em.createQuery("SELECT c FROM Customer WHERE c.login = :login AND c.password = :password")
//                    .setParameter("login", login)
//                    .setParameter("password", password).getSingleResult();
        } catch (Throwable th) {
            throw new EBookshopException(th.getMessage(), th);
        }
    }

    @Override
    public void createCustomer(Customer customer) {
        try {
            em.persist(customer);
        } catch (Throwable th) {
            throw new EBookshopException(th.getMessage(), th);
        }    
    }
    
}
